package draw.server.activityStatus.operate;

import draw.controller.param.DrawPrizesData;
import draw.dao.mapper.ActivityPrizeMapper;
import draw.dao.mapper.ActivityUserMapper;
import draw.server.dto.ActivityUserDto;
import draw.server.enums.ActivityStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.List;

@Slf4j
@Component
public class UserOperate extends AbstractOperate {

    @Autowired
    ActivityUserMapper activityUserMapper;
    @Autowired
    ActivityPrizeMapper activityPrizeMapper;
    @Override
    public int sequence() {
        return 1;
    }

    @Override
    public Boolean needConvert(DrawPrizesData param) {

        List<Long> list = param.getWinnerList().stream().map(DrawPrizesData.LuckUserList::getUserId).toList();

        List<ActivityUserDto> aus = activityUserMapper.getUsersByAUIds(param.getActivityId(), list);

        if (aus.isEmpty()) {
            log.warn("没有相关的活动信息");
            return false;
        }

        if (param.getWinnerList().size() != aus.size()) {
            log.warn("获奖人数和库中人信息的数据不对 Winner: {}  SQL_User: {}", param.getWinnerList(), aus);
            return false;
        }

        for (ActivityUserDto a : aus) {
            if (ActivityStatusEnum.USER_COMPLETED.equals(a.getStatus())) {
                log.warn("有人已经中奖了 user:{}", a);
                return false;
            }
        }

        return true;
    }

    @Override
    public Boolean convert(DrawPrizesData param) {
        if (param == null) {
            log.warn("param is null");
            return false;
        }

        List<Long> ids = param.getWinnerList().stream()
                .map(DrawPrizesData.LuckUserList::getUserId)
                .toList();

        try {
            activityUserMapper.updateStatus(param, ids, ActivityStatusEnum.USER_COMPLETED);
        }catch (Exception e) {
            log.error("扭转活动状态出现错误 param: {}, errorInfo:{}", param + " " + ids + " " + ActivityStatusEnum.USER_COMPLETED,
                    e.getMessage());

            return false;
        }


        return true;
    }
}
